import axios from 'axios';
import {atom, selector,selectorFamily} from 'recoil';

export const demoNum = atom({
  key:"demoNum",
  default:0
})

export const todoListState = atom({
  key: 'todoListState',
  default: [],
});

export const fruitList = atom({
  key:"fruitList",
  default:[]
})

export const todoListFilterState = atom({
  key: 'todoListFilterState',
  default: 'Show All',
});

export const filteredTodoListState = selector({
  key: 'filteredTodoListState',
  get: ({get}) => {
    const filter = get(todoListFilterState);
    const list = get(todoListState);

    switch (filter) {
      case 'Show Completed':
        return list.filter(item => item.isComplete);
      case 'Show Uncompleted':
        return list.filter(item => !item.isComplete);
      default:
        return list;
    }
  },
});

export const showDemoNum = selector({
  key:"showDemoNum",
  get:({get}) =>{
    console.log("showDemoNum",get(demoNum));
    const val= get(demoNum)*2;
    return{
      val
    }
  },
  set:({set}, newValue)=>{
    console.log(newValue);
    set(demoNum,newValue)
  }
})

export const todoListStatsState = selector({
  key: 'todoListStatsState',
  get: ({get}) => {
    const todoList = get(todoListState);
    const totalNum = todoList.length;
    const totalCompletedNum = todoList.filter(item => item.isComplete).length;
    const totalUncompletedNum = totalNum - totalCompletedNum;
    const percentCompleted =
      totalNum === 0 ? 0 : (totalCompletedNum / totalNum) * 100;

    return {
      totalNum,
      totalCompletedNum,
      totalUncompletedNum,
      percentCompleted,
    };
  },
});


export const currentBaidu = selector({
  key: "currentBaidu",
  get: async ({ get }) => {
    console.log("111");
    const response = await axios.get("http://localhost:5656/list");
    console.log("cb",response);
    if (response.error) {
      throw response.error;
    }
    return response.data.data;
  },
  set:({set}, newValue)=>{
    console.log("86",newValue);
    set(fruitList,newValue)
  }
});